package com.cgc.venus.server.app.service;

import com.cgc.venus.server.app.inter.AppStoreService;
import com.cgc.venus.server.core.base.AbstractBaseService;
import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.harbor.HarborService;
import com.cgc.venus.server.core.harbor.model.Tag;
import com.cgc.venus.server.core.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 应用商店功能模块
 * Created by 业哥 on 2017/9/20.
 */
@Service
@ConfigurationProperties(prefix = "app")
public class AppStoreServiceImpl extends AbstractBaseService implements AppStoreService {
    @Autowired
    private HarborService harborServiceImpl;
    private String storeProject;
    private String repositoryUrl;

    public String getRepositoryUrl() {
        return repositoryUrl;
    }

    public void setRepositoryUrl(String repositoryUrl) {
        this.repositoryUrl = repositoryUrl;
    }

    public String getStoreProject() {
        return storeProject;
    }

    public void setStoreProject(String storeProject) {
        this.storeProject = storeProject;
    }

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Map<String, Object>> appTypeQuery(String queryKey) throws VenusException {
        String sql = "";
        List<Map<String, Object>> obj = null;
        if (StringUtil.isEmpty(queryKey)) {
            sql = "SELECT id, name, described FROM t_app_type ORDER BY last_update_time DESC";
            obj = jdbcTemplate.queryForList(sql);
        } else {
            sql = "SELECT id, name, described FROM t_app_type WHERE NAME LIKE ? OR Described LIKE ? ORDER BY last_update_time DESC";
            obj = jdbcTemplate.queryForList(sql, "%" + queryKey + "%", "%" + queryKey + "%");
        }
        return obj;
    }

    @Transactional
    @Override
    public Boolean appTypeAdd(String type, String desc) throws VenusException {
        if (StringUtil.isEmpty(type)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空!");
        }
        //db插入
        String sql = "INSERT INTO t_app_type(id,name,Described,create_time,last_update_time) VALUES (?,?,?,NOW(),NOW())";
        int row = jdbcTemplate.update(sql, StringUtil.getUUID(), type, desc);
        if (row == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Transactional
    @Override
    public Boolean appTypeUpdate(String id, String type, String desc) throws VenusException {
        if (StringUtil.isEmpty(id)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型Id为空!");
        }
        if (StringUtil.isEmpty(type)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空!");
        }
        String sql = "update t_app_type t set t.name=?,t.Described=?,t.last_update_time=NOW() where t.id=?";
        int row = jdbcTemplate.update(sql, type, desc, id);
        if (row == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Transactional
    @Override
    public Boolean appTypeDelete(String id) throws VenusException {
        if (StringUtil.isEmpty(id)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型Id为空!");
        }
        String sql = "delete from t_app_type where id=?";
        int row = jdbcTemplate.update(sql, id);
        if (row == 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 已上架
     * @param queryKey
     * @param appType
     * @return
     * @throws VenusException
     */
    @Override
    public List<Map<String, Object>> appQueryGround(String queryKey, String appType) throws VenusException {
        String sql = "SELECT app.id, app.`name`, type.`name` AS type, rep.pull_count, concat(?,app.`name`) AS imageUrl FROM t_repository_app_store app LEFT JOIN t_app_type type ON type.id = app.app_type LEFT JOIN repository rep ON rep. NAME = app. NAME LEFT JOIN project p ON p.project_id = rep.project_id WHERE p.`name` = ? ";
        List<Map<String, Object>> obj = null;
        List<Object> parm=new ArrayList<Object>();
        parm.add(repositoryUrl);
        parm.add(storeProject);

        //AND type.id = '' AND app.`name` LIKE '%%' ORDER BY app.create_time DESC";
        if (!StringUtil.isEmpty(queryKey)) {
            sql +=" AND app.`name` LIKE ?";
            parm.add("%" + queryKey + "%");
        }
        if(!StringUtil.isEmpty(appType)){
            sql +=" AND type.id =?";
            parm.add(appType);
        }
        sql +="ORDER BY app.create_time DESC";
        return jdbcTemplate.queryForList(sql,parm.toArray());
    }

    /**
     * 未上架应用查询
     * @param queryKey
     * @return
     * @throws VenusException
     */
    @Override
    public List<Map<String, Object>> appQueryOnGround(String queryKey) throws VenusException {
        String sql = "SELECT rep.repository_id AS id, rep.`name`, rep.pull_count, concat(?, rep.`name`) AS imageUrl FROM repository rep LEFT JOIN project p ON p.project_id = rep.project_id WHERE p.`name` = ? AND rep.`name` NOT IN ( SELECT NAME FROM t_repository_app_store ) ";
        List<Object> parm=new ArrayList<Object>();
        parm.add(repositoryUrl);
        parm.add(storeProject);

        //AND rep.`name` LIKE '%k8s%' ORDER BY rep.pull_count DESC
        if (!StringUtil.isEmpty(queryKey)) {
            sql +=" AND rep.`name` LIKE ?";
            parm.add("%" + queryKey + "%");
        }
        sql +=" ORDER BY rep.pull_count DESC";
        List<Map<String, Object>> list=jdbcTemplate.queryForList(sql,parm.toArray());
        return list;
    }

    @Transactional
    @Override
    public Boolean appAdd(String name, String appType, String desc) throws VenusException {
        if (StringUtil.isEmpty(name)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为为空!");
        }
        if (StringUtil.isEmpty(appType)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空!");
        }
        //db插入
        String sql = "INSERT INTO t_repository_app_store(id,name,app_type,Described,create_time,last_update_time) VALUES (?,?,?,?,NOW(),NOW())";
        int row = jdbcTemplate.update(sql, StringUtil.getUUID(),name,appType,desc);
        if (row == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Transactional
    @Override
    public Boolean appDelete(String[] appIds) throws VenusException {
        if(appIds==null||appIds.length==0){
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用Id为空!");
        }
        String sql = "delete from t_repository_app_store where id=?";
        List<Object[]> params=new ArrayList<Object[]>();
        Object[] param=null;
        for(String appId:appIds){
            param=new Object[1];
            param[0]=appId;
            params.add(param);
        }
        int[] row = jdbcTemplate.batchUpdate(sql,params);
        if (row !=null&&row.length==appIds.length) {
            return true;
        } else {
            return false;
        }
    }

    @Transactional
    @Override
    public Boolean appUnGroundDelete(String name) throws VenusException {
        if (StringUtil.isEmpty(name)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为空!");
        }
        return harborServiceImpl.repositoryDelete(name);
    }


}